package com.shengqin.calculate.events.listeners;

import com.shengqin.calculate.data.CalculateSummaryModel;
import com.shengqin.calculate.events.CalculateSummaryEvent;
import com.shengqin.entity.TestResult;
import com.shengqin.service.ISummaryResultService;
import com.shengqin.service.ITestResultService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class CalculateSummaryListener {

  @Resource
  private ISummaryResultService summaryResultService;
  @Resource
  private ITestResultService testResultService;

  @SneakyThrows
  @EventListener(CalculateSummaryEvent.class)
  @Async
  public void onApplicationEvent(CalculateSummaryEvent event) {
    CalculateSummaryModel model = event.getModel();

    List<String> studyCodes = new ArrayList<>();
    studyCodes.add(model.getStudyCode());
    List<TestResult> testResults = testResultService.listByPlanIdAndStudyCodes(model.getPlan().getId(),studyCodes);
//    log.info("开始计算学籍号【{}】的成绩{}条", model.getStudyCode(), testResults.size());
    model.setTestResultList(testResults);
    try {
      summaryResultService.singleSummaryResult(model);
    } catch (Exception e) {
      log.error("计算学籍号总成绩{}报错",model.getStudyCode(),e);
    }
  }
}